//
//  SNKTabBarController.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/8.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKTabBarView.h"

#import "SNKTabBarController.h"
#import "SNKNewsPageController.h"
#import "SNKNavigationController.h"
#import "SNKPhotoViewController.h"
#import "SNKVideoNavController.h"
#import "SNKMeViewController.h"

@interface SNKTabBarController ()

@property (nonatomic, strong) SNKTabBarView *customTabBar;

@end

@implementation SNKTabBarController

- (BOOL)shouldAutorotate {
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTabBar];
    
    [self setupControllers];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    for (UIView *child in self.tabBar.subviews) {
        if ([child isKindOfClass:[UIControl class]]) {
            [child removeFromSuperview];
        }
    }
}

- (void)selectIndex:(int)index {
    [self.customTabBar selectIndex:index];
}

- (void)setupTabBar {
    IMP_BLOCK_SELF(SNKTabBarController);
    SNKTabBarView *customTabBar = [[SNKTabBarView alloc] init];
    customTabBar.frame = self.tabBar.bounds;
    customTabBar.btnSelectBlock = ^(NSInteger to){
        block_self.selectedIndex = to;
    };
    [self.tabBar addSubview:customTabBar];
    self.customTabBar = customTabBar;
    
}

- (void)setupControllers {
    
    SNKNewsPageController *news = [[SNKNewsPageController alloc] init];
    [self setupChildViewController:news title:@"新闻" imageName:@"tabbar_news" selectedImage:@"tabbar_news_hl"];
    
    SNKPhotoViewController *photo = [[SNKPhotoViewController alloc] init];
    [self setupChildViewController:photo title:@"图片" imageName:@"tabbar_picture" selectedImage:@"tabbar_picture_hl"];
    
    SNKVideoNavController *video = [[SNKVideoNavController alloc] init];
    [self setupChildViewController:video title:@"视频" imageName:@"tabbar_video" selectedImage:@"tabbar_video_hl"];
    
    SNKMeViewController *me = [[SNKMeViewController alloc] init];
    [self setupChildViewController:me title:@"我的" imageName:@"tabbar_setting" selectedImage:@"tabbar_setting_hl"];
}

- (void)setupChildViewController:(UIViewController *)childVc title:(NSString *)title imageName:(NSString *)imageName selectedImage:(NSString *)selectedImage {
    
    // 设置控制器属性
    childVc.title = title;
    childVc.tabBarItem.image = [UIImage imageNamed:imageName];
    childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    // 包装一个导航控制器
    SNKNavigationController *nav = [[SNKNavigationController alloc] initWithRootViewController:childVc];
    [self addChildViewController:nav];
    
    [self.customTabBar addTabBarButtonWithItem:childVc.tabBarItem];

}


@end
